package tech.daoxuan.security.browser.authentication;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;
import org.springframework.stereotype.Component;
import tech.daoxuan.security.core.properties.LoginType;
import tech.daoxuan.security.core.properties.SecurityProperties;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Author daoxuan
 * @Date 2019/6/20 20:35
 *
 * {@link SavedRequestAwareAuthenticationSuccessHandler} 是 默认的成功处理类
 *
 * 由 实现 顶级父类的接口，改为 继承 默认实现类，利于 根据不同的需要，返回方式的不通
 *
 *  需要JSON 的  走 自定义
 *  需要 跳转的 ，走默认实现。相当于 扩展了一些方法
 *
 *  同样 失败一样处理
 */
@Component
public class DaoxuanAuthenticationSeccessHandler extends SavedRequestAwareAuthenticationSuccessHandler {
    private  Logger logger = LoggerFactory.getLogger(getClass());

    /**
     * 在spring mvc 启动时 会创建 此对象，此处 引进来即可
     */
    @Autowired
    private ObjectMapper objectMapper;

    @Autowired
    private SecurityProperties securityProperties;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        logger.info("登陆成功");
        //是json 就 返回 json
        if (LoginType.JSON.equals(securityProperties.getBrowser().getLoginType())){
        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().write(objectMapper.writeValueAsString(authentication));
        }else {
            //调用父类的方法 ，从缓存中读取 url跳转
            super.onAuthenticationSuccess(request,response,authentication);
        }

    }
}
